#include "inet_address.h" 
#include <assert.h> 
#include <string.h> 

inet_address::inet_address(u16 port) {
    memset(&this->addr_, 0x00, sizeof(struct sockaddr_in));

    this->addr_.sin_family = AF_INET;
    this->addr_.sin_addr.s_addr = INADDR_ANY;
    this->addr_.port = htons(port);

    this->set_string();
}

inet_address::inet_address(const std::string& ip, u16 port) {
    memset(&this->addr_, 0x00, sizeof(struct sockaddr_in));

    this->addr_.sin_family = AF_INET;
    int ret = inet_pton(this->addr_.sin_family, ip.c_str(), &this->addr_.sin_addr);
    assert(ret == 1);
    this->addr_.sin_port = htons(port);
    
    this->set_string();
}

inet_address::inet_address(const sockaddr_in &addr) {
    memcpy(&this->addr_, &addr, sizeof(this->addr_));

    this->set_string();
}

inet_address::set_string() {
    char addr[64] = {0};
    char host[32] = "INVALID";

    u16 port = ntohs(this->addr_.sin_port);
    const char *ret = inet_ntop(this->addr_.sin_family, this->addr_.sin_addr, host, sizeof(host));
    assert(ret);

    snprintf(addr, sizeof(addr), "%s:%u", hsot, port);

    host_ = host;
    full_ = addr;
}
